package com.hanzhu.consumer.controller;


import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.List;
import java.util.concurrent.ThreadLocalRandom;

@RestController
@Slf4j
public class ConsumerController {

    @Autowired
    private DiscoveryClient discoveryClient;

    @Autowired
    private RestTemplate restTemplate;

    @GetMapping("/instances")
    public List<ServiceInstance> instances(){
        List<ServiceInstance> providerServiceInstances = this.discoveryClient.getInstances("provider");
        return providerServiceInstances;
    }


/*    @GetMapping("/index")
    public String index(){

        //调用provider服务的index方法
        // 1、找到provider实例
        List<ServiceInstance> providerServiceInstances = this.discoveryClient.getInstances("provider");
        int index = ThreadLocalRandom.current().nextInt(providerServiceInstances.size());
        ServiceInstance providerServiceInstance = providerServiceInstances.get(index);
        String url = providerServiceInstance.getUri()+"/index";
        // 2、调用
        log.info("调用端口为 {}",providerServiceInstance.getPort());
        return "调用端口为：" + providerServiceInstance.getPort() + "的服务,返回结果为"+ this.restTemplate.getForObject(url,String.class);
    }*/

    @GetMapping("/index")
    public String index(){
        // ribbon 负载均衡 默认轮询 依次调用
        return restTemplate.getForObject("http://provider/index",String.class);
    }

}
